

#import "GatheringListViewController.h"

#import "UIViewExt.h"
#import "HttpRequest.h"
#import "GatheringListCell.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
#import "UIButton+WebCache.h"
#import "TheLoginViewController.h"
#import "GatheringDetailViewController.h"
#import "GatheringListModel.h"
#import "FilterView.h"
@interface GatheringListViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,FilterViewDelegate>
@end
@implementation GatheringListViewController

{
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*modelArray;
    NSMutableArray*searchBeans;
    int pageNumber;
    BOOL saveAccount;
    UIButton*  screeningBtn;
    UITableView *table;
}
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 0.5)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    self.title=@"历史账单";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addFooter];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) ];
    table.delegate = self;
    table.dataSource = self;
    [table registerClass:[GatheringListCell class] forCellReuseIdentifier:@"GatheringListViewController"];
    modelArray=[[NSMutableArray alloc]init];
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    screeningBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0,  60/2, 60/2)];
    [screeningBtn setImage:[UIImage imageNamed:@"shaixuan"] forState:UIControlStateNormal];
  [screeningBtn addTarget:self action:@selector(sxuan:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:screeningBtn];
    self.navigationItem.rightBarButtonItem = myBtnBtn;
    [self requestData];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"gathering" forKey:@"filterType"];
  
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Common/AdvancedFilterList" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
        
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
}
-(void)requestData{
    
    pageNumber = 1;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:@"20" forKey:@"pageSize"];
    [param setValue:searchBeans forKey:@"searchBeans"];
    [HttpRequest requestData:@"Business/Gathering/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                if (searchBeans.count>0) {
                    [screeningBtn setImage:[UIImage imageNamed:@"shaixuan_hight"] forState:UIControlStateNormal];
                    }else{
                   [screeningBtn setImage:[UIImage imageNamed:@"shaixuan"] forState:UIControlStateNormal];
                }
                
                NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                for (NSDictionary *dic in mItemsArray) {
                    GatheringListModel *dataModel=[GatheringListModel dataModelWithDict:dic];
                    [modelArray addObject:dataModel];
                    
                }
                [table reloadData];
                
            }else{
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];

}

//上拉刷新
- (void)addFooter
{
    
    
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        if (Token ==nil) {
            Token=@"dd";
        }
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        [param setValue:@"1" forKey:@"pageIndex"];
        [param setValue:@"20" forKey:@"pageSize"];
        [param setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
        [param setValue:searchBeans forKey:@"searchBeans"];
        [HttpRequest requestData:@"Business/Gathering/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
            
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    NSMutableArray* arrr=[[NSMutableArray alloc]init];
                    arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                    NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                    for (NSDictionary *dic in mItemsArray) {
                        GatheringListModel *dataModel=[GatheringListModel dataModelWithDict:dic];
                        [modelArray addObject:dataModel];
                        }
                    [table reloadData];
                    
                }else{
                    
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                        
                        TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
                        [self.navigationController pushViewController:detailViewController animated:YES];
                    }
                }
                
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
            
        }];

        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
    
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [table reloadData];
    [refreshView endRefreshing];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    

    return [modelArray count];
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    return  80;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GatheringListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GatheringListViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model=modelArray[indexPath.row];
    
                  return cell;
    }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GatheringListModel *ScreeningModel=modelArray[indexPath.row];

    GatheringDetailViewController *detailViewController = [[GatheringDetailViewController alloc] init];
        detailViewController.gid=ScreeningModel.orderId;
        [self.navigationController pushViewController:detailViewController animated:YES];

}



#pragma mark - Table view delegate


//清空购物车
-(void)empty:(UIButton*)sender{
    
    
    UIAlertView*alt1 = [[UIAlertView alloc] initWithTitle:@"是否清空购物车！" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alt1 show];
    
    
}
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
//上拉刷新
- (void)addheader
{
    MJRefreshHeaderView* footer = [MJRefreshHeaderView header];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        searchBeans=nil;
//        commdity.content3=@"";
        [self requestData];
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:3.0f];
        //        NSLog(@"%@--->正在刷新", mainScroll.class);
    };

}
-(void)sxuan:(UIButton*)sender{
    FilterView *filterView=[FilterView FilterViewWithSize:CGSizeMake(ScreenWidth, ScreenHeight)];
    filterView.typeStr=@"gathering";
    filterView.delegate=self;
    filterView.selectedSearchBeansArray=searchBeans;
    [filterView show];
    
}
#pragma mark FilterViewDelegate
-(void)confirmFilter:(NSMutableArray *)searchBeansArray
{
    searchBeans=searchBeansArray;
    [self requestData];
}

@end
